﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.Generic;
using System.Threading.Tasks;
using TabbedTemplate.Models;
using TabbedTemplate.Services;
using Xamarin.Forms.Extended;

namespace TabbedTemplate.ViewModels
{
    public class QueryResultPageViewModel : ViewModelBase
    {
        //******** 绑定属性

        /// <summary>
        /// 标签。
        /// </summary>
        public ClassifySearchParameter Query
        {
            get => _query;
            set => Set(nameof(Query), ref _query, value);
        }

        /// <summary>
        /// 标签。
        /// </summary>
        private ClassifySearchParameter _query;

        public string queryName;

        public double Lat { get; set; }

        public int PageNum { get; set; }

        /// <summary>
        /// 是否为新查询。
        /// </summary>
        private bool _newQuery;

        public const string Loading = "正在载入";

        public const string NoResult = "没有满足条件的结果";

        public const string NoMoreResult = "没有更多结果";

        public string Status
        {
            get => _status;
            set => Set(nameof(Status), ref _status, value);
        }

        private string _status;


        /// <summary>
        /// 店铺存储服务
        /// </summary>
        private readonly IStoreService _storeService;

        private readonly IPreferenceStorage _preferenceStorage;
        private readonly IQueryService _queryService;
        private ILocationService _locationService;
        private readonly IPunchNavigationService _punchNavigationService;
        public bool QueryCanLoadMore;

        public InfiniteScrollCollection<Store> QueryStoreCollection { get; }

        public QueryResultPageViewModel(IStoreService storeService,
            IPreferenceStorage preferenceStorage, IQueryService queryService,
            ILocationService locationService,
            IPunchNavigationService punchNavigationService)
        {
            _newQuery = true;
            _storeService = storeService;
            _preferenceStorage = preferenceStorage;
            _queryService = queryService;
            _locationService = locationService;
            _punchNavigationService = punchNavigationService;
            QueryStoreCollection = new InfiniteScrollCollection<Store>();
        }

        /// <summary>
        /// 页面初始化命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ??= new RelayCommand(async () =>
                await PageAppearingCommandFunction());

        public async Task PageAppearingCommandFunction()
        {
            if (!_newQuery && queryName == Query.Input)
            {
                return;
            }

            if (queryName != Query.Input)
            {
                QueryStoreCollection.Clear();
            }

            PageNum = 0;
            QueryStoreCollection.Clear();
            QueryStoreCollection.OnCanLoadMore = () => QueryCanLoadMore;
            QueryStoreCollection.OnLoadMore = async () =>
            {
                if (Query.Input == "")
                {
                    queryName = Query.Tag;
                }
                else
                {
                    queryName = Query.Input;
                }
                Status = Loading;
                string cityName = _preferenceStorage.Get("City", "北京市");

                if (!_queryService.Initialized())
                {
                    await _queryService.InitializeAsync();
                }

                var res =
                    await _queryService.GetSearchItemByString(Query.Input,
                        cityName);
                //新的搜索，从web中获取
                if (!res.HasCache)
                {
                    await _queryService.InsertSearchItem(queryName,
                        cityName);
                    if (Query.Tag == "")
                    {
                        SearchResults =
                            await _storeService
                                .SearchStoresByRegionFromWebAsync(
                                    "美食;" + Query.Input, cityName,
                                    QueryStoreCollection.Count /
                                    StoreService.PageSize);
                    }
                    else
                    {
                        SearchResults =
                            await _storeService
                                .SearchStoresByRegionClassifyFromWebAsync(
                                    Query.Tag, Query.Input, cityName,
                                    QueryStoreCollection.Count /
                                    StoreService.PageSize);
                    }
                }
                else
                {
                    //历史搜索过从数据库中读取
                    SearchResults =
                        await _storeService
                            .SearchStoresByRegionClassifyFromWebAsync(
                                Query.Tag, Query.Input, cityName,
                                QueryStoreCollection.Count /
                                StoreService.PageSize);
                }


                if (SearchResults.Count < StoreService.PageSize)
                {
                    QueryCanLoadMore = false;
                    Status = NoMoreResult;
                }
                else
                {
                    Status = "";
                }

                if (QueryStoreCollection.Count == 0 &&
                    SearchResults.Count == 0)
                {
                    Status = NoResult;
                }

                return SearchResults;
            };
            QueryCanLoadMore = true;
            await QueryStoreCollection.LoadMoreAsync();

            //var tempList = QueryStoreCollection.Where(p => p.Tag.Contains(Query.Tag)).ToList();
            //QueryStoreCollection.Clear();
            //QueryStoreCollection.AddRange(tempList);
            _newQuery = false;
        }

        private RelayCommand<Store> _storeTappedCommand;

        public RelayCommand<Store> StoreTappedCommand =>
            _storeTappedCommand ??= new RelayCommand<Store>(async store =>
                await PoetryTappedCommandFunction(store));

        public async Task PoetryTappedCommandFunction(Store store) =>
            await _punchNavigationService.NavigateToAsync(
                ContentNavigationConstant.StorePunchesPage, store);

        private List<Store> _searchResults;

        public List<Store> SearchResults
        {
            get => _searchResults;
            set => Set(nameof(SearchResults), ref _searchResults, value);
        }
    }
}
